<?php

namespace app\admin\controller;

use app\common\model\IpVisit;
use app\common\model\MbtiTests;
use think\facade\Db;
use think\facade\Filesystem;
use Ip2Region;

class Index
{
    public function index()
{
    // 获取每个 IP 的访问总量
    $ipVisits = Db::name('ip_visits')->order('id', 'desc')
        ->where('create_time', '>=', date('Y-m-d', strtotime("-2 day")))
        ->paginate(100);
    // print_r($ipVisits->toArray());die;
    $rs = [];
    $newData = is_object($ipVisits)  ? $ipVisits->toArray():[];
    $count = count($newData['data']); // 注意 paginate 返回的结果在 'data' 键里
    for ($i = 0; $i < $count; $i++) {
        $current = $newData['data'][$i];
        if ($i + 1 < $count) {
            $next = $newData['data'][$i + 1];
            $rs[] = [
                'id' => $current['id'],
                'ip1' => $current['ip'],
                'ip1_create_time' => $current['create_time'],
                'id2' => $next['id'],
                'ip2' => $next['ip'],
                'ip2_create_time' => $next['create_time']
            ];
            $i++; // 跳过下一个元素，避免重复处理
        } else {
            // 如果没有下一个元素，单独处理当前元素
            $rs[] = [
                'id' => $current['id'],
                'ip1' => $current['ip'],
                'ip1_create_time' => $current['create_time'],
                'id2' => '',
                'ip2' => '',
                'ip2_create_time' => ''
            ];
        }
    }
     $ipClass = new Ip2Region();
//   $ipClass = new Ip2Region();
    foreach ($rs as &$item) {
        $select1 = $ipClass->btreeSearch($item['ip1'])['region'] ?? "";
        // print_r($select1);die;
        $item['area1'] = str_replace(["0|","中国|","|0"],'',$select1);
          if(!empty($item['ip2'])){
                      $select2 = $ipClass->btreeSearch($item['ip2'])['region'] ??"";

                 $item['area2'] = str_replace(["0|","中国|","|0"],'',$select2);   
        }else{
            $item['area2'] = '';
        }
    }
    return view('admin/index', ['list' => $ipVisits,'rs'=>$rs]);
}



    public function logout()
    {
        session("user_id", null);
        return redirect(url('/admins/login'));
    }
    public function login()
    {
        $user['user_id'] = 1;
        $user['password'] = '48215104';
        $user['username'] = 'dalei';

        if (request()->isPost()) {
            $data = input('post.');
            if ($data['username'] != $user['username'] || $data['password'] != $user['password']) {
                return toJson(1, '密码输入错误', "");
            }
            session('username', $user['username']);
            session('user_id', $user['user_id']);
            return toJson(0, '登录成功', "");
        }
        return view('admin/login');
    }

    /**
     * 上传
     * @return false|\think\response\Json
     */
    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        $path = '';
        //写入到表中
        $mine = $file->getOriginalMime();
        $ext = $file->extension();
        $fileName = $file->getFilename();
        if (!in_array($ext, ['png', 'jpg', 'gif', "jpeg", "mp4"])) {
            return false;
        }
        if ($ext == 'mp4') {
            if (abs($file->getSize() / 1024) > 51200) {
                return false;
            }
        }
        if (abs($file->getSize() / 1024) > 3048) {
            return false;
        }
        // 上传到本地服务器
        $filename = date('Ym') . '/' . date('YmdHis') . mt_rand(1000, 9999);
        $file = Filesystem::disk('public')->putFile($path, $file, function () use ($filename) {
            return $filename;
        });
        return toJson(0,'ok',['/storage/'.$file]);
    }
}